<!-- eslint-disable vue/no-required-prop-with-default -->
<script lang="tsx" setup>
import type { DataTableColumn } from 'naive-ui';
import { NButton } from 'naive-ui';
import type { ComponentInternalInstance } from 'vue';
import { getCurrentInstance, ref, watch } from 'vue';
import type { UserVO } from '@/service/types/system';
defineOptions({
  name: 'ExportModal'
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const exportVisible = defineModel<boolean>('exportVisible', {
  default: false
});
const radioType = ref<string>('all');
const loading = ref<boolean>(false);
const checkedField = ref();
const indeterminate = ref(false);
const fieldList = ref();
const checkedRef = ref<boolean>(false);
interface Props {
  columns: DataTableColumn<UserVO>[] | unknown;
  title?: string;
  searchParams: any;
  url: string;
  // eslint-disable-next-line vue/no-unused-properties
  params?: any;
  fileName?: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: '导出',
  url: '',
  params: {} as any,
  searchParams: {} as any,
  fileName: `${new Date().getTime()}.xlsx`
});
const closeModal = () => {
  exportVisible.value = false;
  fieldList.value = [];
  checkedRef.value = false;
  indeterminate.value = false;
  radioType.value = 'all';
};
const resetModal = () => {
  radioType.value = 'all';
};
const handleClose = () => {
  closeModal();
  resetModal();
};
watch(exportVisible, () => {
  if (exportVisible.value) {
    const updatedColumns = props.columns
      // 过滤掉 type 为 "selection" 和 key 为 "operate" 的项
      .filter(column => column.type !== 'selection' && column?.key !== 'operate')
      // 只保留 key 和 title 属性
      .map(({ key, title }) => ({ key, title }));
    fieldList.value = updatedColumns;
    checkedRef.value = true;
    indeterminate.value = false;
    checkedField.value = updatedColumns.map((column: { key: any }) => {
      return column.key;
    });
  }
});
const handleCheckedChange = (checked: boolean) => {
  checkedRef.value = checked;
  if (!checked) {
    // 如果为true就全选
    checkedField.value = [];
    return;
  }
  checkedField.value = fieldList.value.map((column: { key: any }) => {
    return column.key;
  });
};
const handleValue = (value: Array<string | number>) => {
  if (value.length === fieldList.value.length) {
    indeterminate.value = false;
    if (fieldList.value !== 0) {
      checkedRef.value = true;
    }
  } else if (value.length === 0) {
    checkedRef.value = false;
    indeterminate.value = false;
  } else {
    indeterminate.value = true;
  }
};

const downloadUserData = async (params: any) => {
  proxy
    ?.download({
      url: props.url,
      dataParams: params,
      params: {},
      fileName: props.fileName
    })
    .then(() => {
      loading.value = false;
      closeModal();
    })
    .catch(() => {
      loading.value = false;
    });
};
const handleExportData = async () => {
  loading.value = true;
  const formParams = JSON.parse(JSON.stringify(props.searchParams));
  // 处理参数
  const requestParams = {
    ...props.params,
    ...formParams,
    fieldList: checkedField.value,
    exportType: radioType.value
  };
  await downloadUserData(requestParams);
};
</script>

<template>
  <NModal v-model:show="exportVisible" :title="props.title" preset="card" class="w-800px" @esc="handleClose">
    <NSpace vertical class="mb-10px">
      <NRadioGroup v-model:value="radioType" name="radius">
        <NRadioButton value="all" label="导出全部数据" />
        <NRadioButton value="page" label="当前页" />
      </NRadioGroup>
    </NSpace>
    <NSpace vertical>
      <div>导出项</div>
      <div>
        <NSpace>
          <NCheckbox
            value="all"
            label="全选"
            :checked="checkedRef"
            :indeterminate="indeterminate"
            @update:checked="handleCheckedChange"
          />
        </NSpace>
      </div>
      <NSpace>
        <NCheckboxGroup v-model:value="checkedField" @update:value="handleValue">
          <NCheckbox
            v-for="column in fieldList"
            :key="column.key"
            size="large"
            :value="column.key"
            :label="column.title"
          />
        </NCheckboxGroup>
      </NSpace>
    </NSpace>
    <template #footer>
      <NSpace justify="end">
        <NButton @click="handleClose">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleExportData">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped></style>
